<template>
  <div>
    <!-- 添加修改的不能为空表单验证 -->
    <el-button type="primary" class="addRolesBut" @click="openAddRolesDialog"
      >添加角色<i class="el-icon-circle-plus-outline el-icon--right"></i
    ></el-button>
    <!-- 角色列表 -->
    <el-table :data="rolesDate" border stripe style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <!-- 一级权限 -->
            <el-row
              :class="['bdbottom', key == 0 ? 'bdtop' : '', 'center']"
              v-for="(item, key) in props.row.children"
              :key="item.id"
            >
              <el-col :span="5">
                <el-tag closable @close="removeTag(props.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  :class="[key2 == 0 ? '' : 'bdtop', 'center']"
                  v-for="(val, key2) in item.children"
                  :key="val.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeTag(props.row, val.id)"
                      >{{ val.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级权限 -->
                    <el-tag
                      type="warning"
                      v-for="v in val.children"
                      :key="v.id"
                      closable
                      @close="removeTag(props.row, v.id)"
                    >
                      {{ v.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column type="index" label="#" width="60"> </el-table-column>
      <el-table-column prop="roleName" label="角色名称"> </el-table-column>
      <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <!-- 修改按钮 -->
          <el-button
            type="warning"
            icon="el-icon-edit"
            circle
            @click="showRolesEdit(scope.row)"
          ></el-button>
          <!-- 删除按钮 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="removeRoleEdit(scope.row)"
          ></el-button>
          <!-- 分配权限按钮 -->
          <el-button
            size="small"
            type="warning"
            icon="el-icon-setting"
            @click="showRolesRight(scope.row)"
          >
            分配权限
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加角色弹出框 -->
    <el-dialog title="添加角色" :visible.sync="dialogRolesAdd" width="60%">
      <el-form :model="addRolesList" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名称">
          <el-input v-model="addRolesList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRolesList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addRoles">确 定</el-button>
        <el-button @click="dialogRolesAdd = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息弹出框 -->
    <el-dialog title="修改用户信息" :visible.sync="dialogRolesEdit" width="60%">
      <el-form :model="roleEditData" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色ID">
          <el-input v-model="roleEditData.id" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="roleEditData.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleEditData.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editRole">确 定</el-button>
        <el-button @click="editcancel">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限弹出框 -->
    <el-dialog title="分配权限" :visible.sync="dialogRightChange" width="60%">
      <!-- 树形控件 -->
      <el-tree :data="rightData" :props="rightProps"  show-checkbox node-key="id" default-expand-all
      :default-checked-keys="defkey"	ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addRights"
          >确 定</el-button
        >
        <el-button @click="dialogRightChange = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  //import 引入组件
  components: {},
  data() {
    return {
      // 角色列表数据
      rolesDate: [],
      dialogRolesAdd: false,
      dialogRolesEdit: false,
      dialogRightChange: false,
      //增加角色列表
      addRolesList: {},
      //修改角色列表
      roleEditData: {},
      // 权限列表
      rightData: [],
      // 树形控件
      rightProps: {
        label: "authName",
        children: "children",
      },
      //默认选中权限的id值
      defkey:[],
      // 分配权限选中的角色id
      roleid:''
    };
  },
  methods: {
    //获取角色列表
    async getRolesData() {
      const { data } = await this.$axios.get("/roles");
      if (data.meta.status == 200) {
        this.rolesDate = data.data;
      } else {
        this.$message.error(data.meta.msg);
      }
    },
    //打开添加弹出框
    openAddRolesDialog() {
      this.dialogRolesAdd = true;
    },
    //增加角色确认事件
    async addRoles() {
      const { data } = await this.$axios.post("/roles", this.addRolesList);
      console.log(data);
      if (data.meta.status == 201) {
        this.addRolesList = data.data;
        this.getRolesData();
        this.$message({
          type: "success",
          message: data.meta.msg,
        });
      } else {
        this.$message.error(data.meta.msg);
      }
      this.dialogRolesAdd = false;
    },
    // 打开修改角色弹出框
    showRolesEdit(info) {
      this.dialogRolesEdit = true;
      this.roleEditData = info;
      console.log(this.roleEditData);
    },
    // 确认修改
    async editRole() {
      const { data } = await this.$axios.put(
        "/roles/" + this.roleEditData.id,
        this.roleEditData
      );
      if (data.meta.status == 200) {
        this.$message({
          type: "success",
          message: "修改成功",
        });
      } else {
        this.$message.error(data.meta.msg);
      }
      this.dialogRolesEdit = false;
    },
    //取消修改
    editcancel() {
      this.dialogRolesEdit = false;
      // 重新渲染当前列表还原回去
      this.getRolesData();
    },
    //删除按钮功能
    removeRoleEdit(userinfo) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data } = await this.$axios.delete("/roles/" + userinfo.id);
          if (data.meta.status == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //删除更新局部列表
            this.getRolesData();
          } else {
            this.$message.error(data.meta.msg);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //删除Tag标签
    async removeTag(roles, rightId) {
      const confirmRes = await this.$confirm(
        "此操作将永久删除该标签, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmRes !== "confirm") {
        return this.$message.info("已取消");
      }
      // 确认删除
      const { data } = await this.$axios.delete(
        `/roles/${roles.id}/rights/${rightId}`
      );
      if (data.meta.status !== 200) {
        this.$message.error(data.meta.msg);
      }
      // 赋值直接更新
      roles.children = data.data;
    },
    // 打开分配权限对话框
    async showRolesRight(role) {
      this.dialogRightChange = true;
      //获取三级节点前清空上一次获取的节点
      this.defkey=[];
      this.roleid=role.id
    // 获取权限列表
      const {data} = await this.$axios.get("/rights/tree");
        // console.log(data);
      if (data.meta.status == 200) {
        this.rightData = data.data;
      } else {
        return this.$message.error(data.meta.msg);
      }
      // 传参获取三级节点
      this.getDefKey(role,this.defkey)
    },
    // 获取三级节点
    getDefKey(info,arr){
      if(!info.children){
        return arr.push(info.id)
      }
      info.children.forEach(item => 
        this.getDefKey(item,arr)
      );
    },
    // 分配权限确认按钮
    async addRights(){
      //获取所有被选中的id用数组保存
      const keys=[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      //把选中的id转成字符串
      const idStr=keys.join(',')
      // 传入选中的id，添加id对应权限
      const {data}=await this.$axios.post(`roles/${this.roleid}/rights`,{rids:idStr})
      if(data.meta.status==200){
        this.getRolesData();
         this.$message({
          type: "success",
          message: data.meta.msg,
        });
      }else{
        return this.$message.error(data.meta.msg);
      }
      this.dialogRightChange = false;
    }
  },
  mounted() {
    this.getRolesData();
  },
};
</script>

<style>
.addRolesBut {
  float: left;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.center {
  display: flex;
  align-items: center;
}
</style>
